package com.wms.ymcc.mq;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wms.ymcc.constant.ValidationConstants;
import com.wms.ymcc.domain.PayOrder;
import com.wms.ymcc.exception.GlobalBaseException;
import com.wms.ymcc.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @author : 阿盛哟
 * @description :消费订单发送的事务消息
 * @createDate : 2025/6/23 14:23
 */
@RocketMQMessageListener(topic = ValidationConstants.MQ_TOPIC_ORDER,
        selectorExpression = ValidationConstants.MQ_TAGS_COURSEORDER_PAYORDER,
        consumerGroup = "service-pay-consumer-order")
@Service
@Slf4j
public class MQTXConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    /**
     * 消费
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1. 获取到消息
        try {
            // 一定有消息，才处理
            if(messageExt!=null && messageExt.getBody()!=null && messageExt.getBody().length>0){

                byte[] body = messageExt.getBody();
                String s = new String(body, "UTF-8");
                // 转成 payOrder对象
                PayOrder payOrder = JSONObject.parseObject(s, PayOrder.class);

                log.info("拿到消息：{}",payOrder);

                // 查询t_pay_order是否已经存在该支付单了。查orderNo，防止已经生成的该支付单
                Wrapper<PayOrder> ww = new EntityWrapper<>();
                ww.eq("order_no",payOrder.getOrderNo());
                PayOrder payOrderFormDB = payOrderService.selectOne(ww);
                if(payOrderFormDB==null){
                    payOrderService.insert(payOrder);
                }else {
                    log.error("支付单已存在，不能重复添加");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new GlobalBaseException("生成支付单失败");
        }


    }
}